package supplier

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"
	"strings"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetSupplierPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetSupplierPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetSupplierPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetSupplierPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetSupplierPageApiLogic) GetSupplierPageApi(req *types.GetSupplierPageReq) (resp *types.SupplierPageResp, err error) {
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	offset, limit := utils.DbPage(req.PageNumber, req.PageSize)
	tx := dao.SupplierEntity.WithContext(l.ctx).Where(dao.SupplierEntity.EnterpriseID.Eq(enterpriseId))
	if req.Name != "" {
		req.Name = strings.ReplaceAll(req.Name, "%", "\\%")
		req.Name = strings.ReplaceAll(req.Name, "_", "\\%")
		tx = tx.Where(dao.SupplierEntity.Name.Like("%" + req.Name + "%"))
	}
	if req.Status != "" {
		tx = tx.Where(dao.SupplierEntity.Status.Eq(cast.ToInt64(req.Status)))
	}

	supplierEntities, count, err := tx.Order(dao.SupplierEntity.Sort, dao.SupplierEntity.ID.Desc()).FindByPage(offset, limit)
	if err != nil {
		return &types.SupplierPageResp{
			Data: make([]types.SupplierModel, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      count,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	supplierModels := k.Map(supplierEntities, func(item *model.SupplierEntity, index int) types.SupplierModel {
		return types.SupplierModel{
			ID:        item.ID,                                 // 主键id
			Name:      item.Name,                               // 单位名称
			Sort:      item.Sort,                               // 排序
			Status:    item.Status,                             // 状态:1是正常,2是禁用
			Describe:  item.Describe,                           // 描述
			CreatedAt: utils.TimestampToString(item.CreatedAt), // 创建时间
			UpdatedAt: utils.TimestampToString(item.UpdatedAt), // 更新时间
		}
	})
	return &types.SupplierPageResp{
		Data: supplierModels,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
